#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json

from flask import Blueprint
from flask import render_template
from flask import request
from flask import flash
from flask import redirect
from flask import url_for
from flask_login import login_required

from app.models import User, Role
from app.utils.decorators import admin_required
from app import app, db

bp = Blueprint('admin', __name__,  template_folder='templates',
               static_folder='static')


@bp.route('/index', methods=['GET'])
@login_required
@admin_required
def index():
    users = User.query.all()
    return render_template('admin/index.html', users=users)


@bp.route('/roles', methods=['GET'])
@login_required
@admin_required
def roles():
    roles = Role.query.all()
    roles_list = [{'value': role.id, 'text': role.name_zh} for role in roles]
    return json.dumps(roles_list)


@bp.route('/create', methods=['POST'])
@login_required
@admin_required
def create():
    username = request.form.get('username')
    password = request.form.get('password')
    role = request.form.get('role') or 2
    user = User.query.filter_by(username=username)
    if user.count():
        flash(u"用户名已经存在",category='danger')
        return redirect(url_for('admin.index'))
    u = User(username=username, password=password, role_id=role)
    db.session.add(u)
    db.session.commit()
    flash(u'创建用户成功', category='success')
    return redirect(url_for('admin.index'))


@bp.route("/change", methods=["POST"])
@login_required
@admin_required
def change():

    username = request.form.get('pk')  # username
    value = request.form.get('value')
    name = request.form.get('name')

    if name not in ("role_id", "password", "deleted"):
        return "update error", 500

    try:
        user = User.query.filter_by(username=username).first()
        user.change(name, value)
        db.session.add(user)
        db.session.commit()
        return "ok", 200

    except Exception as e:
        app.logger.error("change user %s failed." % name)
        db.session.rollback()
        return "update err", 500
